package com.ningxia.water.controller;

import com.ningxia.water.configuration.PredictLiner;
import com.ningxia.water.entity.TsWellInfo;
import com.ningxia.water.entity.TsWellWarn;
import com.ningxia.water.enums.WarnCodeEnum;
import com.ningxia.water.enums.WellStatusEnum;
import com.ningxia.water.reuslt.Result;
import com.ningxia.water.reuslt.ResultResponse;
import com.ningxia.water.service.*;
import com.ningxia.water.utils.CommonUtils;
import com.ningxia.water.utils.NumberUtils;
import com.ningxia.water.vo.out.MeterInfoVo;
import com.ningxia.water.vo.out.MonthConsumedVo;
import com.ningxia.water.vo.out.WellInfoVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.ListIterator;

/**
 * @author huangzhen
 * @create 2021-03-16 19:57
 * 机井信息的CURD
 */
@RestController
@RequestMapping("/wellinfo")
@Api(tags = "基本信息-机井信息Api")
public class WellInfoController {

    @Autowired
    private ITsWellInfoService wellInfoService;

    @Autowired
    private ITsWellMeterService wellMeterService;

    @Autowired
    private ITsMeterService meterService;

    @Autowired
    private ITsDayDataService dayDataService;

    @Autowired
    private ITsMonthDataService monthDataService;

    @Autowired
    private ITsWellWarnService wellWarnService;


    private PredictLiner predictLiner = new PredictLiner();

    @GetMapping("/getwellinfos")
    @ApiOperation(value = "获取机井的全部信息")
    public Result getWellInfos() {
        List<WellInfoVo> allInfos = wellInfoService.getWellInfos();
        //封装结果并返回
        return ResultResponse.getSuccessResult(allInfos);
    }


    @GetMapping("/getwellinfobywellid")
    @ApiOperation("通过机井id查询机井详情")
    public Result getWellInfoByWellId(@RequestParam("wellId") Integer wellId) {
        return ResultResponse.getSuccessResult(wellInfoService.getById(wellId));
    }

    /**
     * 根据条件查询机井
     *
     * @param applicantName 用水户名称
     * @param wellCode      机井编码
     * @param wellName      机井名称
     * @param address       地址
     * @param wellType      机井类型
     * @param status        机井状态
     * @param zoneType      所属区域类型：1是工业园区，2是村
     * @return
     */
    @GetMapping("/findwellinfosbyconditions")
    @ApiOperation(value = "根据条件查询机井")
    public Result findWellInfosByConditions(@RequestParam(value = "applicantName", required = false) String applicantName,
                                            @RequestParam(value = "wellCode", required = false) String wellCode,
                                            @RequestParam(value = "wellName", required = false) String wellName,
                                            @RequestParam(value = "address", required = false) String address,
                                            @RequestParam(value = "wellType", required = false) Integer wellType,
                                            @RequestParam(value = "status", required = false) Integer status,
                                            @RequestParam(value = "zoneType", required = false) Integer zoneType) {
        List<WellInfoVo> allInfos = wellInfoService.findWellInfosByConditions(applicantName, wellCode, wellName, address, wellType, status, zoneType);
        //封装结果并返回
        return ResultResponse.getSuccessResult(allInfos);
    }

    /**
     * 添加
     *
     * @param wellInfo
     * @return
     */
    @PostMapping("/insertwellinfo")
    @ApiOperation(value = "新增机井信息")
    public Result insertWellInfo(@RequestBody TsWellInfo wellInfo, @RequestParam("applicantId") Integer applicantId) {
        boolean flag = wellInfoService.insertWellInfo(wellInfo, applicantId);
        boolean f2 = true;
        //判断是否是4444报警状态的机井，如果是就加入报警表中
        if (WellStatusEnum.MALFUNCTION.getCode().equals(wellInfo.getStatus())) {
            TsWellWarn tsWellWarn = new TsWellWarn(WarnCodeEnum.VOLUME_EXPRESS.getCode(), wellInfo.getWellId(), 0, LocalDateTime.now(),applicantId);
            wellWarnService.save(tsWellWarn);
        }
        return CommonUtils.commonResult(flag && f2);
    }


    /**
     * 更新
     *
     * @param wellInfo
     * @return
     */
    @PutMapping("/updatewellinfo")
    @ApiOperation(value = "更新机井信息")
    public Result updateWellInfo(@RequestBody TsWellInfo wellInfo) {
        boolean flag = wellInfoService.updateById(wellInfo);
        boolean f2 = true;
        if (WellStatusEnum.MALFUNCTION.getCode().equals(wellInfo.getStatus())) {
            TsWellWarn tsWellWarn = new TsWellWarn(WarnCodeEnum.VOLUME_EXPRESS.getCode(), wellInfo.getWellId(), 0, LocalDateTime.now());
            Integer applicantId = wellInfoService.findApplicantIdByWellId(wellInfo.getWellId());
            tsWellWarn.setApplicantId(applicantId);
            wellWarnService.save(tsWellWarn);
        }
        return CommonUtils.commonResult(flag && f2);
    }


    /**
     * 删除
     *
     * @param wellId
     * @return
     */
    @DeleteMapping("/deletewellinfo")
    @ApiOperation(value = "删除机井信息")
    public Result deleteWellInfo(@RequestParam("well_id") Integer wellId) {
        //机井下是否有设备
        Integer count = wellMeterService.findWellMeters(wellId);
        if (count > 0) {
            return ResultResponse.getFailResult("此机井存在设备，无法删除！");
        } else {
            return CommonUtils.commonResult(wellInfoService.removeById(wellId));
        }
    }


    /**
     * 通过机井id查找设备详情
     *
     * @param wellId
     * @return
     */
    @GetMapping("/findmeterbywellid")
    @ApiOperation(value = "通过机井id查找设备详情")
    public Result findMeterByWellId(@RequestParam("wellId") Integer wellId) {
        List<MeterInfoVo> meterInfos = meterService.findByWellId(wellId);
        return ResultResponse.getSuccessResult(meterInfos);
    }


    @GetMapping("/findvolumebytime")
    @ApiOperation(value = "根据机井ID和时间范围来查找累计用水量")
    public Result findVolumeByWellIdAndTime(@RequestParam("well_id") Integer well_id,
                                            @RequestParam("startTime") String startTime,
                                            @RequestParam("endTime") String endTime) {
        Double t = dayDataService.findVolumeByWellIdAndTime(well_id, startTime, endTime);
        return ResultResponse.getSuccessResult(t);
    }

    /**
     * 根据机井id获取今年累计水量
     *
     * @param well_id
     * @return
     */
    @GetMapping("/findvolumebyyear")
    @ApiOperation(value = "根据机井id获取本年累计水量")
    public Result findVolumeByYear(@RequestParam("well_id") Integer well_id) {
        String year = String.valueOf(LocalDateTime.now().getYear());
        Double t = dayDataService.findVolumeByYear(well_id, year);
        return ResultResponse.getSuccessResult(NumberUtils.getInstance().format(new BigDecimal(t)));
    }

    /**
     * 根据机井id获取日、月、年累计水量
     *
     * @param well_id
     * @return
     */
    @GetMapping("/findvolumebyday")
    @ApiOperation(value = "根据机井id获取日、月、年累计水量")
    public Result findVolumeByDay(@RequestParam("well_id") Integer well_id,
                                  @RequestParam("type") String type,
                                  @RequestParam("time") String time) {
        Double t = dayDataService.findVolumeByTime(well_id, type, time);
        return ResultResponse.getSuccessResult(t);
    }


    /**
     * 根据机井id获取每个月的累计水量
     *
     * @param wellId
     * @return
     */
    @GetMapping("/findmonthvolumebyyear")
    @ApiOperation(value = "根据机井id获取每个月的累计水量")
    public Result findMonthVolumeByYear(@RequestParam("wellId") Integer wellId,
                                        @RequestParam("year") String year) {

        //获取每月消耗用水量
        List<MonthConsumedVo> list = monthDataService.getMonthConsumedByWellId(wellId, year);
        return ResultResponse.getSuccessResult(list);
    }
    @GetMapping("/getmonthpredict")
    @ApiOperation("预测下一个月用水的信息")
    public Result getWaterPredict(@RequestParam("wellId") Integer wellId,
                                  @RequestParam("year") String year){
        List<MonthConsumedVo> list = monthDataService.getMonthConsumedByWellId(wellId, year);
        System.out.println(list);
        if(list.size()==0){
            return ResultResponse.getSuccessResult("Null");
        }
        String []MonthVolumeData = new String[list.size()];
        ListIterator<MonthConsumedVo> iterator = list.listIterator();
        int n = 0;
        while (iterator.hasNext()) {
            MonthConsumedVo next = iterator.next();
            MonthVolumeData[n] = String.valueOf(next.getVolume());
            if(n+1< list.size())n++;
        }
        System.out.println(MonthVolumeData[0]);
        double a = predictLiner.predictMonthVolumeByWeek(MonthVolumeData);
        return ResultResponse.getSuccessResult(a);
    }
    @GetMapping("/predictvolumebyyear")
    @ApiOperation(value = "根据三年年用水量预测年用水量")
    public Result predictVolumeByYear(@RequestParam("well_id") Integer well_id) {
        String year = String.valueOf(LocalDateTime.now().getYear());
        String beforeyear = String.valueOf(LocalDateTime.now().getYear()-1);
        String beforeyear1 = String.valueOf(LocalDateTime.now().getYear()-2);
        Double t = dayDataService.findVolumeByYear(well_id, year);
        if(t==null)t=0.0;
        Double t1= dayDataService.findVolumeByYear(well_id, beforeyear);
        if(t1==null)t1=0.0;
        Double t2= dayDataService.findVolumeByYear(well_id, beforeyear1);
        if(t2==null)t2=0.0;
        List<Double> temp = new ArrayList<>();
        String []yearvolume = new String[]{String.valueOf(t),String.valueOf(t1),String.valueOf(t2)};
        temp.add(t);
        temp.add(t1);
        temp.add(t2);
        double data = predictLiner.predictYearVolumeByYear(yearvolume);
        return ResultResponse.getSuccessResult(data);
    }
    @GetMapping("/predictbreakbytime")
    @ApiOperation(value = "根据三年年用水量预测年用水量")
    public Result predictBreakByTime(@RequestParam("hour") Integer hour,
                                     @RequestParam("minute") Integer minute,
                                     @RequestParam("temperature") double temperature) {
        String []a = new String[]{String.valueOf(hour),String.valueOf(minute),String.valueOf(temperature)};
        //String []a = {"1","2","22"};
        double data = predictLiner.predictBreakByPressure(a);
        return ResultResponse.getSuccessResult(data);
    }

}
